<template>
    <el-container style="display: block;">
        <el-row type="flex" :gutter="0" style="flex-wrap: nowrap;">
            <el-col :style="{ flex: '0 0 300px', maxWidth: '300px' }" :xs="0" :sm="0" :md="0" :lg="3" :xl="3">
                <!-- 左侧题目列表侧边栏 -->
                <LeftSidebar 
                    :question-list="questionList"
                    :question-id="questionId"
                />
            </el-col>
            <el-col :style="{ flex: '1 1 auto', }" :xs="24" :sm="21" :md="21" :lg="18" :xl="18">
                <el-main>
                    <el-card class="question-title-card">
                        <div>
                            <h2 class="question-title">{{ questionDetail.title }}</h2>
                            <div class="question-tag" style="margin-top: 15px;">
                                <el-tag v-if="questionDetail.isVip" class="no-border" type="warning" size="small" effect="dark" color="#fed73b">VIP</el-tag>
                                <el-tag class="no-border" type="danger" size="small" effect="dark" :color="difficultyColor">{{ questionDetail.difficultyName }}</el-tag>
                                <el-tag v-for="tagName in questionDetail.tagNameList" :key="tagName" type="info" size="small" effect="plain">{{ tagName }}</el-tag>
                            </div>
                            <div class="question-content"  style="margin-top: 15px;">
                                <div v-html="questionDetail.content"></div>
                            </div>
                            <div class="question-actions flex mt-5!">
                                <el-button link type="info" size="small">
                                    <svg class="icon" aria-hidden="true">
                                        <use xlink:href="#icon-tag"></use>
                                    </svg>标记
                                </el-button>
                                <el-button link type="info" size="small">
                                    <svg class="icon" aria-hidden="true">
                                        <use xlink:href="#icon-share"></use>
                                    </svg>分享
                                </el-button>
                                <el-button link type="info" size="small">
                                    <svg class="icon" aria-hidden="true">
                                        <use xlink:href="#icon-star"></use>
                                    </svg>649
                                </el-button>
                                <el-button link type="info" size="small">
                                    <svg class="icon" aria-hidden="true">
                                        <use xlink:href="#icon-eye"></use>
                                    </svg>43243
                                </el-button>
                            </div>
                        </div>
                    </el-card>
                    <el-tabs v-model="activeTab" style="margin-top: 15px; background-color: #fff; padding: 20px;padding-bottom: 6px; border:1px solid #e4e7ed; border-radius: 4px;">
                        <el-tab-pane label="推荐答案" name="first">
                            <div v-html="questionDetail.answer" class="question-answer"></div>
                            <div class="answer-actions flex" style="padding-top:6px;margin-top:12px; border-top: 1px solid #e4e7ed;">
                                <div class="flex-1">
                                    <el-button link type="info" size="small" style="width: 100%; height:36px; border-right: 1px solid #e4e7ed;">
                                        <svg class="icon" aria-hidden="true">
                                            <use xlink:href="#icon-like"></use>
                                        </svg>199
                                    </el-button>
                                </div>
                                <div class="flex-1">
                                    <el-button link type="info" size="small" style="width: 100%; height:36px;">
                                        <svg class="icon" aria-hidden="true">
                                            <use xlink:href="#icon-sound"></use>
                                        </svg>催更
                                    </el-button>
                                </div>
                                <div class="flex-1">
                                    <el-button link type="info" size="small" style="width: 100%; height:36px; border-left: 1px solid #e4e7ed;">
                                        <svg class="icon" aria-hidden="true">
                                            <use xlink:href="#icon-edit-square"></use>
                                        </svg>反馈
                                    </el-button>
                                </div>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="测试一下" name="second">
                            <div class="question-test">
                                <p>
                                    测试一下
                                </p>
                                <p>
                                    测试一下
                                </p>
                                <p>
                                    测试一下
                                </p>
                            </div>
                            <el-button type="primary" class="my-3!" size="large">提交答案</el-button>
                        </el-tab-pane>
                    </el-tabs>
                    <el-card class="question-switch" style="margin-top: 15px;">
                        <div class="flex justify-between p-0">
                            <div class="text-left">
                                <p class="mb-3!">
                                    上一题
                                </p>
                                <el-button 
                                    link 
                                    type="primary"
                                    :disabled="!hasPrevQuestion"
                                    @click="goPrevQuestion"
                                >
                                    <svg class="icon" aria-hidden="true">
                                        <use xlink:href="#icon-doubleleft"></use>
                                    </svg>
                                    <span>{{ prevQuestion?.title || '已是第一题' }}</span>
                                </el-button>
                            </div>
                            <div class="text-right">
                                <p class="mb-3!">
                                    下一题
                                </p>
                                <el-button 
                                    link 
                                    type="primary"
                                    :disabled="!hasNextQuestion"
                                    @click="goNextQuestion"
                                >
                                    <span>{{ nextQuestion?.title || '已是最后一题' }}</span>
                                    <svg class="icon" style="margin: 0 0 0 7px" aria-hidden="true">
                                        <use xlink:href="#icon-doubleright"></use>
                                    </svg>
                                </el-button>
                            </div>
                        </div>
                    </el-card>
                    <el-tabs v-model="activeDisscus" class="question-discuss" style="margin-top: 15px; background-color: #fff; padding: 20px;padding-bottom: 6px; border:1px solid #e4e7ed; border-radius: 4px;">
                        <el-tab-pane label="回答讨论（199个）" name="discuss">
                            <div class="discuss-content mt-5!">
                                <li class="flex mt-5!" style="list-style: none;">
                                    <el-col :span="2">
                                        <div class="user-avatar">
                                            <el-avatar :size="38" :src="userStore.user.avatarUrl || loginUrl" />
                                        </div>
                                    </el-col>
                                    <el-col :span="22">
                                        <div class="user-name" style="font-size: 16px;">
                                            <strong>用户名</strong>
                                        </div>
                                        <div class="discuss-content mt-3!">
                                            <p>
                                                导航菜单默认为垂直模式，通过将 mode 属性设置为 horizontal 来使导航菜单变更为水平模式。 另外，在菜单中通过 sub-menu 组件可以生成二级菜单。 Menu 还提供了background-color、text-color和active-text-color，分别用于设置菜单的背景色、菜单的文字颜色和当前激活菜单的文字颜色。
                                            </p>
                                        </div>
                                        <div class="discuss-actions my-3!" style="color:#999">
                                            <span>2023-08-01 12:00:00</span>
                                            <el-button class="ml-5!" type="white" size="small" style="border:none">
                                                <svg class="icon" aria-hidden="true" style="font-size: 10px;">
                                                    <use xlink:href="#icon-like"></use>
                                                </svg>0
                                            </el-button>
                                            <el-button class="ml-3!" type="white" size="small" style="border:none">
                                                <svg class="icon" aria-hidden="true" style="font-size: 10px;">
                                                    <use xlink:href="#icon-star"></use>
                                                </svg>0
                                            </el-button>
                                            <el-button class="ml-3!" type="white" size="small" style="border:none">
                                                <svg class="icon" aria-hidden="true" style="font-size: 10px;">
                                                    <use xlink:href="#icon-message"></use>
                                                </svg>回复
                                            </el-button>
                                        </div>
                                    </el-col>
                                </li>
                                <li class="flex mt-5!" style="list-style: none;">
                                    <el-col :span="2">
                                        <div class="user-avatar">
                                            <el-avatar :size="38" :src="userStore.user.avatarUrl || loginUrl" />
                                        </div>
                                    </el-col>
                                    <el-col :span="22">
                                        <div class="user-name" style="font-size: 16px;">
                                            <strong>用户名</strong>
                                        </div>
                                        <div class="discuss-content mt-3!">
                                            <p>
                                                导航菜单默认为垂直模式，通过将 mode 属性设置为 horizontal 来使导航菜单变更为水平模式。 另外，在菜单中通过 sub-menu 组件可以生成二级菜单。 Menu 还提供了background-color、text-color和active-text-color，分别用于设置菜单的背景色、菜单的文字颜色和当前激活菜单的文字颜色。
                                            </p>
                                        </div>
                                        <div class="discuss-actions my-3!" style="color:#999">
                                            <span>2023-08-01 12:00:00</span>
                                            <el-button class="ml-5!" type="white" size="small" style="border:none">
                                                <svg class="icon" aria-hidden="true" style="font-size: 10px;">
                                                    <use xlink:href="#icon-like"></use>
                                                </svg>0
                                            </el-button>
                                            <el-button class="ml-3!" type="white" size="small" style="border:none">
                                                <svg class="icon" aria-hidden="true" style="font-size: 10px;">
                                                    <use xlink:href="#icon-star"></use>
                                                </svg>0
                                            </el-button>
                                            <el-button class="ml-3!" type="white" size="small" style="border:none">
                                                <svg class="icon" aria-hidden="true" style="font-size: 10px;">
                                                    <use xlink:href="#icon-message"></use>
                                                </svg>回复
                                            </el-button>
                                        </div>
                                    </el-col>
                                </li>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="我的回答" name="my-discuss">
                            <div class="question-discuss">
                                <div class="flex my-discuss mt-3!">
                                    <el-col :span="2">
                                        <div class="user-avatar">
                                            <el-avatar :size="38" :src="userStore.user.avatarUrl || loginUrl" />
                                        </div>
                                    </el-col>
                                    <el-col :span="22">
                                        <div class="my-discuss-content">
                                            <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
                                                <Toolbar
                                                    style="border-bottom: 1px solid #ccc"
                                                    :editor="disscusEditorRef"
                                                    :defaultConfig="toolbarConfig"
                                                    :mode="'simple'"
                                                />
                                                <Editor
                                                    style="height: 320px; overflow-y: hidden;"
                                                    :defaultConfig="editorConfig"
                                                    :mode="'simple'"
                                                    @onCreated="handleDiscussCreated"
                                                />
                                            </div>
                                            <el-button type="primary" class="my-3!" size="large">发布回答</el-button>
                                        </div>
                                    </el-col>
                                </div>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </el-main>
            </el-col>
            <el-col :style="{ flex: '0 0 300px', maxWidth: '300px' }" :xs="0" :sm="3" :md="3" :lg="3" :xl="3" style="margin-top: 20px;">
                <!-- 右侧侧边栏 -->
                <RightSiderbar />
            </el-col>
        </el-row>
    </el-container>
    <!-- 工具栏 -->
    <ToolBar />
</template>
<script lang="ts" setup name="question">
    import { ref, onMounted, watch, nextTick, computed, shallowRef } from 'vue';
    import { useRoute,useRouter, onBeforeRouteUpdate  } from 'vue-router';
    import { Http } from '@/network/request';
    import { QuestionItem, QuestionListResponse, QuestionDetail } from '@/views/question/data.d';
    
    import { useUserStore } from '@/store/user'
    import loginUrl from '@/assets/avatar.gif'
    import { ElMessage } from 'element-plus';

    //引入子组件
    import LeftSidebar from '@/views/question/components/LeftSidebar.vue'
    import RightSiderbar from '@/views/question/components/RightSiderbar.vue'
    import ToolBar from '@/views/question/components/ToolBar.vue'
    
    // 引入highlight.js实现代码高亮显示
    import hljs from 'highlight.js';
    import 'highlight.js/styles/atom-one-dark.css';

    const route = useRoute();
    const router = useRouter();
    // 定义当前激活的标签页，默认值为第一个标签页的 name
    const activeTab = ref('first');
    const activeDisscus = ref('discuss')

    //定义题目列表和题目详情的响应式变量
    const questionList = ref<QuestionItem[]>([]);
    const questionDetail = ref<QuestionDetail>({} as QuestionDetail);
    const loading = ref(true)

    //从URL参数中获取题目分类id和题目id
    const categoryId = ref(route.params.bankId);
    const questionId = ref(route.params.questionId);

    const userStore = useUserStore()

    // 引入wangEditor
    import '@wangeditor/editor/dist/css/style.css' // 引入 css
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
    import { IEditorConfig, IToolbarConfig } from '@wangeditor/editor'

    // 为内容和答案分别创建编辑器实例
    const disscusEditorRef = shallowRef()

    // 处理内容编辑器创建
    const handleDiscussCreated = (editor: any) => {
    disscusEditorRef.value = editor
    }

    const toolbarConfig: Partial<IToolbarConfig> = {
        insertKeys:{
            index: 23,
            keys: ['uploadVideo'],
        }
    }

    type InsertFnType = (data: string) => void
    const editorConfig: Partial<IEditorConfig> = {
        // 初始化 MENU_CONF 属性
        MENU_CONF: {
            uploadImage: {
            fieldName: 'file', // 上传图片的字段名
            maxNumberOfFiles: 10, // 最多可上传几个文件，默认为 100
            base64LimitSize: 5 * 1024, // 小于5kb就插入 base64 格式（而不上传）
            allowedFileTypes: ['image/*'], //文件类型限制
            async customUpload(file: File, insertFn: InsertFnType) {
                const formData = new FormData()
                formData.append('file', file)  // 确保使用正确字段名
                
                try {
                const res = await Http.post('/file/upload', formData, {
                    headers: {
                    'Content-Type': 'multipart/form-data'  // 必须设置请求头
                    }
                })
                
                if (res.code === 0 && res.data) {
                    insertFn(res.data as string)  // 根据实际返回结构调整
                }
                } catch (error) {
                    ElMessage.error('图片上传失败')
                }
            }
            },
            uploadVideo:{
            fieldName: 'file', // 上传视频的字段名
            maxFileSize: 5 * 1024 * 1024, //单个文件的最大体积限制5M
            maxNumberOfFiles: 5, //最多可上传几个文件
            allowedFileTypes: ['video/*'], //文件类型限制
            async customUpload(file: File, insertFn: InsertFnType) {
                const formData = new FormData()
                formData.append('file', file)  // 确保使用正确字段名
                
                try {
                const res = await Http.post('/file/upload', formData, {
                    headers: {
                    'Content-Type': 'multipart/form-data'  // 必须设置请求头
                    }
                })
                
                if (res.code === 0 && res.data) {
                    insertFn(res.data as string)  // 根据实际返回结构调整

                }
                } catch (error) {
                    ElMessage.error('视频上传失败')
                }
            }
            }
        },
    }

    // 获取题目列表数据
const getQuestionList = async () => {
    try {
        const response = await Http.post('/code-duck-question/listByQuestionCategory', {
            questionCategoryId: categoryId.value,
        });
        if (response && response.data) {
            // 类型断言确保records是QuestionItem数组
            questionList.value = (response.data as QuestionListResponse).records || [];
        } else {
            questionList.value = [];
        }
    } catch (error) {
        console.error('请求失败:', error)
    }
};

// 根据题目列表数据获取当前题目详情数据
const getQuestionDetail = async () => {
    loading.value = true;
    try {
        const question = questionList.value.find(item => item.id === questionId.value);
        if (question) {
            questionDetail.value = question;
            // 保持代码高亮初始化
            nextTick(() => {
                hljs.highlightAll();
            });
        } else {
            console.warn(`未找到ID为${questionId.value}的问题`);
            questionDetail.value = {} as QuestionDetail;
        }
    } catch (error) {
        console.error('获取题目详情失败:', error);
    } finally {
        loading.value = false;
    }
};

// 题目难度根据难度值返回不同的颜色
const difficultyColor = computed(() => {
    switch(questionDetail.value.difficulty) {
        case 0: return '#87D068'; // 简单
        case 1: return '#FD9815'; // 中等
        case 2: return '#FF2D55'; // 困难
        default: return '#87D068'; // 默认简单
    }
});

// 添加自动滚动到激活项的逻辑
const scrollToActiveItem = () => {
    nextTick(() => {
        const activeElement = document.querySelector('.router-active');
        if (activeElement) {
            // 使用scrollIntoView实现滚动，配置平滑滚动和垂直居中
            activeElement.scrollIntoView({
                behavior: 'smooth',
                block: 'nearest',
                inline: 'start'
            });
        }
    });
};

// 页面加载时获取数据
onMounted(async () => {
    if (categoryId.value && questionId.value) {
        await getQuestionList();
        await getQuestionDetail(); // 取消注释并调用
        scrollToActiveItem(); // 页面加载完成后滚动
    } else {
        loading.value = false;
    }
});

// 监听questionId变化，动态更新详情
onBeforeRouteUpdate (async (to) => {
    // 确保参数确实发生了变化才更新
    if (to.params.questionId !== questionId.value) {
        questionId.value = to.params.questionId;
        await getQuestionDetail();
    }
});

// 监听questionId变化，切换题目时也滚动
watch(questionId, async (newId) => {
    if (newId) {
        await getQuestionDetail();
        scrollToActiveItem(); // 题目切换后滚动
    }
});

// 计算属性：获取当前题目索引
const currentIndex = computed(() => {
    return questionList.value.findIndex(item => item.id === questionId.value);
});

// 计算属性：是否有上一题
const hasPrevQuestion = computed(() => {
    return currentIndex.value > 0;
});

// 计算属性：是否有下一题
const hasNextQuestion = computed(() => {
    return currentIndex.value < questionList.value.length - 1;
});

// 计算属性：上一题数据
const prevQuestion = computed(() => {
    if (hasPrevQuestion.value) {
        return questionList.value[currentIndex.value - 1];
    }
    return null;
});

// 计算属性：下一题数据
const nextQuestion = computed(() => {
    if (hasNextQuestion.value) {
        return questionList.value[currentIndex.value + 1];
    }
    return null;
});

// 上一题跳转方法
const goPrevQuestion = () => {
    if (hasPrevQuestion.value) {
        const prevId = questionList.value[currentIndex.value - 1].id;
        router.push(`/bank/${questionDetail.value.questionCategoryId}/question/${prevId}`);
    }
};

// 下一题跳转方法
const goNextQuestion = () => {
    if (hasNextQuestion.value) {
        const nextId = questionList.value[currentIndex.value + 1].id;
        router.push(`/bank/${questionDetail.value.questionCategoryId}/question/${nextId}`);
    }
};
</script>
<style lang="scss" scoped>
    // iconfont
    .icon {
        width: 1.5em;
        height: 1.5em;
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
        margin-right: 0.5em;
    }

    // 题目标题卡片
    .question-title-card{
        .question-tag>.el-tag{
            margin-right: 8px;
        }
    }
    :deep(.no-border) {
        // 取消边框
        border: none; 
    }
    :deep(.hot-title) {
        background: linear-gradient(180deg, #fde68a, #fff) !important;;
    }
    :deep(.recommend) {
        background: linear-gradient(180deg, #fde68a, #fff) !important;;
    }
</style>
